let timeout = 10000
let staticBaseUrl = 'http://47.99.160.107:8090'
import {
	toast,
	showConfirm,
	tansParams
} from '@/utils/common'

const request = config => {
	const userInfo = uni.getStorageSync('userInfo');
	config.header = config.header || {}

	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	return new Promise((resolve, reject) => {
		uni.request({
			method: config.method || 'get',
			timeout: config.timeout || timeout,
			url: staticBaseUrl + config.url,
			data: config.data,
			header: {
				...config.header,
				'Authorization': userInfo.accessToken,
			},
			dataType: 'json'
		}).then(response => {
			let [error, res] = response
			console.log(res, 'res')
			if (error) {
				toast('请检查网络')
				reject('后端接口连接异常')
				return
			}
			if (res.data.data) {
				resolve(res.data.data)
			} else {
				reject(res.data.msg)
			}
		}).catch(error => {
			let {
				message
			} = error
			if (message === 'Network Error') {
				message = '后端接口连接异常'
			} else if (message.includes('timeout')) {
				message = '系统接口请求超时'
			} else if (message.includes('Request failed with status code')) {
				message = '系统接口' + message.substr(message.length - 3) + '异常'
			}
			toast(message)
			reject(error)
		})
	})
}

export default request